<template>
    <chart :id="id" :option="option"></chart>
</template>

<script>
import _ from 'lodash'
import chart from '../chart/chart'
export default {
  name: 'c-bar',
  props: {
    id: {
      type: String,
      required: true
    },
    chartData: {
      type: Array,
      default: () => [
        {
          name: '2012',
          value1: 120,
          value2: 200
        },
        {
          name: '2013',
          value1: 200,
          value2: 130
        },
        {
          name: '2014',
          value1: 150,
          value2: 210
        },
        {
          name: '2015',
          value1: 110,
          value2: 130
        },
        {
          name: '2016',
          value1: 80,
          value2: 70
        },
        {
          name: '2017',
          value1: 70,
          value2: 140
        },
        {
          name: '2018',
          value1: 130,
          value2: 170
        }
      ]
    },
    chartOption: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    'chart': chart
  },
  computed: {
    // 图表配置项
    option () {
      const that = this
      let realData = []
      for (let i = 0; i < that.chartData.length; i++) {
        if (Object.keys(that.chartData[i]).length >= 2) {
          realData.push(that.chartData[i])
        }
      }
      // 通过获取传入对象的属性的个数，生成serieArr
      let serieArr = []
      if (realData && realData[0]) {
        let serieNum = Object.keys(realData[0]).length - 1
        // 基准的barWidth百分比
        let barWidth = (40 / serieNum) + '%'
        for (let i = 0; i < serieNum; i++) {
          serieArr.push({
            type: 'bar',
            barWidth: barWidth
          })
        }
      }
      // 返回默认配置项与传入配置合并后的option，生成图表
      return _.merge({
        dataset: {
          source: realData
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value'
        },
        series: serieArr
      }, that.chartOption)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
